#include "lvgl/lvgl.h"
#include "lvgl/demos/lv_demos.h"
#include "lv_drivers/display/fbdev.h"
#include "lv_drivers/indev/evdev.h"
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <stdio.h>

#include <ui.h>
#include "LED/led_control.h"
#include "BEEP/beep_control.h"
#include "TEMPERATURE/temperature.h"
#include "AIRPOWER/airpower.h"
#include "WEATHER/weather.h"
#include "TIME/time_display.h"


#include <stdio.h>
#include <stdint.h>
#include <unistd.h>

// 正确声明：与定义一致（返回值为int，无参数）
int mqtt_init(void);  
int mqtt_publish_data(void);
int mqtt_is_connected(void);

// 定义5秒上传间隔（5000ms / 5ms = 1000次循环）
#define MQTT_UPLOAD_INTERVAL 1000


#define DISP_BUF_SIZE (128 * 1024)

// // 在main.c中添加函数声明（如果没有头文件）
// extern void mqtt_init(void);
// extern void mqtt_task_handler(void);
// extern void mqtt_cleanup(void);  // 可选



void Btn_Handler(lv_event_t * e)
{
    const char *str = lv_event_get_user_data(e);

    printf("%s\n",str);
}

//显示部件
void widget_obj(void)
{
    lv_obj_t *main_win = lv_scr_act();
    
    //进度条
    /*
    lv_obj_t *bar = lv_bar_create(main_win);
    lv_obj_set_size(bar, 200, 20);
    lv_obj_center(bar);
    lv_bar_set_range(bar,0,100);//设置进度条上限和下限值
    lv_bar_set_value(bar, 70, LV_ANIM_OFF);
    

    //列表框
    lv_obj_t * dir_list  = lv_list_create(main_win); //创建列表控件
    lv_obj_set_size(dir_list,300,480);//设置大小
    //添加按钮
    lv_obj_t * list_btn_wifi = lv_list_add_btn(dir_list,LV_SYMBOL_WIFI,"Net-Work"); 
    lv_obj_t * list_btn_stop = lv_list_add_btn(dir_list,LV_SYMBOL_STOP,"STOP"); 

    lv_obj_add_event_cb(list_btn_wifi,Btn_Handler,LV_EVENT_SHORT_CLICKED,"Net-Work");
    lv_obj_add_event_cb(list_btn_wifi,Btn_Handler,LV_EVENT_SHORT_CLICKED,"STOP");
    */

    lv_obj_set_flex_flow(main_win, LV_FLEX_FLOW_ROW);//设置排成一行

    //复选框
    lv_obj_t *checkBox1 = lv_checkbox_create(main_win);
    lv_checkbox_set_text(checkBox1, "B/S");

    lv_obj_t *checkBox2 = lv_checkbox_create(main_win);
    lv_checkbox_set_text(checkBox2, "M/N");

    lv_obj_t *checkBox3 = lv_checkbox_create(main_win);
    lv_checkbox_set_text(checkBox3, "D/K ");
}

int mqtt_test(void);

int main(void)
{
    /*LittlevGL init*/
    lv_init();

    /*Linux frame buffer device init*/
    fbdev_init();

    /*A small buffer for LittlevGL to draw the screen's content*/
    static lv_color_t buf[DISP_BUF_SIZE];

    /*Initialize a descriptor for the buffer*/
    static lv_disp_draw_buf_t disp_buf;
    lv_disp_draw_buf_init(&disp_buf, buf, NULL, DISP_BUF_SIZE);

    /*Initialize and register a display driver*/
    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);
    disp_drv.draw_buf   = &disp_buf;
    disp_drv.flush_cb   = fbdev_flush;
    disp_drv.hor_res    = 1024;
    disp_drv.ver_res    = 600;
    lv_disp_drv_register(&disp_drv);

    evdev_init();
    static lv_indev_drv_t indev_drv_1;
    lv_indev_drv_init(&indev_drv_1); /*Basic initialization*/
    indev_drv_1.type = LV_INDEV_TYPE_POINTER;

    /*This function will be called periodically (by the library) to get the mouse position and state*/
    indev_drv_1.read_cb = evdev_read;
    lv_indev_t *mouse_indev = lv_indev_drv_register(&indev_drv_1);


    /*Set a cursor for the mouse*/
    LV_IMG_DECLARE(mouse_cursor_icon)
    lv_obj_t * cursor_obj = lv_img_create(lv_scr_act()); /*Create an image object for the cursor */
    lv_img_set_src(cursor_obj, &mouse_cursor_icon);           /*Set the image source*/
    lv_indev_set_cursor(mouse_indev, cursor_obj);             /*Connect the image  object to the driver*/




    // 初始化MQTT（在主循环前调用一次）
    mqtt_init();
        // 用于计数的变量
    uint32_t mqtt_counter = 0;




    // mqtt_test();
    /*Create a Demo*/
    //lv_demo_widgets();
    //widget_obj();
    ui_init();
    // 初始化LED控制
    led_control_init();
    // 在程序初始化部分添加
    beep_control_init();
    // 在系统初始化时
    adc_display_init();         // 初始化ADC显示模块
    adc_display_start();        // 启动ADC读取和显示更新

    airpower_init();    // 初始化模块
    airpower_start();   // 启动数据更新

    // 初始化天气模块（绑定UI元素）
    weather_init();
    
    // 从IP自动获取位置并更新天气
    weather_update_from_ip();

    // 初始化时间显示（依赖桌面UI的ui_desktop对象）
    ui_time_screen_init();

    /*Handle LitlevGL tasks (tickless mode)*/
    while(1) {
        lv_timer_handler();
        // 每5秒上传一次数据
        mqtt_counter++;
        if (mqtt_counter >= MQTT_UPLOAD_INTERVAL) {
            mqtt_publish_data();  // 发布数据
            mqtt_counter = 0;     // 重置计数器
        }
        //mqtt_task_handler();     // MQTT任务处理（上报温度）
        usleep(5000);
    }


    // 程序退出前清理
    lv_task_handler();  // LVGL任务处理
    led_control_cleanup();
    // 在程序退出前添加
    beep_control_cleanup();
    // 在系统退出前
    adc_display_stop();
    // 5. 最终清理资源
    adc_display_cleanup();

    airpower_stop();
    airpower_deinit();  // 释放资源

    // 程序退出时清理
    weather_cleanup();
    return 0;
}

/*Set in lv_conf.h as `LV_TICK_CUSTOM_SYS_TIME_EXPR`*/
uint32_t custom_tick_get(void)
{
    static uint64_t start_ms = 0;
    if(start_ms == 0) {
        struct timeval tv_start;
        gettimeofday(&tv_start, NULL);
        start_ms = (tv_start.tv_sec * 1000000 + tv_start.tv_usec) / 1000;
    }

    struct timeval tv_now;
    gettimeofday(&tv_now, NULL);
    uint64_t now_ms;
    now_ms = (tv_now.tv_sec * 1000000 + tv_now.tv_usec) / 1000;

    uint32_t time_ms = now_ms - start_ms;
    return time_ms;
}
